package main

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

type CMDBInfo struct {
	InstanceName string        `json:"name"`
	RegionCode   string        `json:"region_code"`
	RegionName   string        `json:"region"`
	ZoneCode     string        `json:"region_zone_code"`
	ZoneName     string        `json:"region_zone"`
	Platform     []interface{} `json:"platform"`
}

type Platform struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

var (
	client = &http.Client{Transport: &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
		Timeout: 10 * time.Second,
	}
)

func newHttpRequest(method, url string) (*http.Request, error) {
	var dataBytes []byte
	request, err := http.NewRequest(method, url, bytes.NewReader(dataBytes))
	if err != nil {
		return nil, err
	}
	request.Header.Set("Content-Type", "application/json;charset=utf-8")
	return request, nil
}

func doHttpRequest(request *http.Request) ([]byte, map[string][]string, error) {
	resp, err := client.Do(request)
	if err != nil {
		return nil, nil, err
	}
	if resp.StatusCode != 200 {
		return nil, nil, err
	}
	respBody, err := ioutil.ReadAll(resp.Body)
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)
	if err != nil {
		return nil, nil, err
	}

	return respBody, resp.Header, nil
}

func GetCMDBInfo(instanceIp string) (*CMDBInfo, error) {
	apiURL := fmt.Sprintf("http://10.0.12.80:10112/unicmdb/instance/v1/global-search?content=%s", instanceIp)
	request, err := newHttpRequest("GET", apiURL)
	if err != nil {
		return nil, err
	}
	respBody, _, err := doHttpRequest(request)
	if err != nil {
		return nil, err
	}
	var info []CMDBInfo
	err = json.Unmarshal(respBody, &info)
	if err != nil {
		return nil, errors.New("failed to get cmdb info")
	}
	if len(info) == 0 {
		return nil, errors.New("no data has been found")
	}

	return &info[0], nil
}

func main() {
	//info, err := GetCMDBInfo("10.247.151.178")
	info, err := GetCMDBInfo("10.247.144.32")
	if err != nil {

	}
	if info.Platform != nil {
		platform := info.Platform[0].(map[string]interface{})["key"].(string)
		fmt.Println(platform)
	} else {
		platform := "business"
		fmt.Println(platform)
	}
	fmt.Println(info)
}
